package com.ghy.ic.mo.task;

import com.ghy.ic.mo.dao.BcsVehicleDeliveryInfo;
import com.ghy.ic.mo.utils.JodaTimeUtil;
import org.apache.log4j.Logger;

import java.util.List;

import static com.ghy.ic.mo.constant.BcsConstant.*;

/**
 * @author Y-Tree
 * @date 18-12-4 上午11:28
 */
public class ShuttleBusAddTask implements Runnable {

    private static final Logger LOGGER = Logger.getLogger(ShuttleBusAddTask.class);

    /**
     * 每天下午5：30取消两条记录，再添加两条记录
     */

    @Override
    public void run() {
        LOGGER.info("正在添加一条班车记录中...");

        // 0. 获取当前日期， 根据当前日期+1 结束设置后日期的所有服务
        String currentDate = JodaTimeUtil.getAFewDaysLaterDate(0);
        String nextDayDate = JodaTimeUtil.getAFewDaysLaterDate(1);
        String afterSixteenDaysDate = JodaTimeUtil.getAFewDaysLaterDate(16);

        // 1. 结束下一天日期的所有服务（包含下午和上午）
        List<BcsVehicleDeliveryInfo> infoList = BcsVehicleDeliveryInfo.getVehicleDeliveryInfoByDepartureDate(nextDayDate);
        if (!infoList.isEmpty()){
            for (BcsVehicleDeliveryInfo info : infoList){
                // 将服务状态置为“已结束”
                Integer id = info.getId();
                if(!BcsVehicleDeliveryInfo.updateBySercieStatus(id, END)){
                    LOGGER.error("将状态置为“已结束”失败！");
                }
            }
        }else {
            LOGGER.error("数据库中没有可以取消的服务。");
        }

        // 2. 判断今天的服务是否停止，没有停止则进行停止操作
        List<BcsVehicleDeliveryInfo> currentDateInfoList = BcsVehicleDeliveryInfo.getVehicleDeliveryInfoByDepartureDate(currentDate);
        if (!currentDateInfoList.isEmpty()){
            for (BcsVehicleDeliveryInfo info : infoList){
                // 将服务状态置为“已结束”
                Integer id = info.getId();
                // 表明服务还没有被关闭
                if (info.getServiceStatus() != UNDER_WAY){
                    if(!BcsVehicleDeliveryInfo.updateBySercieStatus(id, END)){
                        LOGGER.error("将状态置为“已结束”失败！");
                    }
                }else {
                    LOGGER.info("当天的服务状态已被置为非“进行中”。");
                }

            }
        }else {
            LOGGER.error("数据库中没有可以取消的服务。");
        }

        // 3. 添加两条记录上午和下午
        // 上午
        BcsVehicleDeliveryInfo forenoon = new BcsVehicleDeliveryInfo();
        forenoon.setTimeMark(FORENOON);
        forenoon.setDepartureDate(afterSixteenDaysDate);
        forenoon.setDepartureTime(FORENOON_TIME);
        if (!BcsVehicleDeliveryInfo.add(forenoon)){
            LOGGER.error("添加上午的记录失败！");
        }

        // 下午
        BcsVehicleDeliveryInfo afternoon = new BcsVehicleDeliveryInfo();
        afternoon.setTimeMark(AFTERNOON);
        afternoon.setDepartureDate(afterSixteenDaysDate);
        afternoon.setDepartureTime(AFTERNOON_TIME);
        if (!BcsVehicleDeliveryInfo.add(afternoon)){
            LOGGER.info("添加下午的记录失败！");
        }

        LOGGER.info("已完成一条班车记录的添加。");
    }
}
